package com.ruoyi.web.controller.common;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.web.service.TokenService;

/**
 * starter请求处理
 * 
 * @author 周江
 */
@RestController
@RequestMapping("/starter")
public class StarterController {
	private static final Logger log = LoggerFactory.getLogger(StarterController.class);

	@Value("${spring.redis.host}")
	private String redisHost;

	@Value("${spring.redis.password}")
	private String redisPassword;

	@Value("${spring.redis.port}")
	private String redisPort;

	@Value("${spring.redis.database}")
	private String redisDatabase;

	@Value("${token.header}")
	private String tokenHeader;

	@Value("${token.secret}")
	private String tokenSecret;

	@Autowired
	TokenService tokenService;

	/**
	 * 同步配置
	 */
	@GetMapping("/syncConfig")
	public AjaxResult syncConfig() {
		log.info("收到同步配置请求");
		Map<String, String> coinfigData = new HashMap<>();
		coinfigData.put("host", redisHost);
		coinfigData.put("port", redisPort);
		coinfigData.put("password", redisPassword);
		coinfigData.put("database", redisDatabase);
		coinfigData.put("header", tokenHeader);
		coinfigData.put("secret", tokenSecret);
		AjaxResult result = AjaxResult.success(coinfigData);
		log.info("返回同步配置结果：{}", result);
		return result;
	}

	/**
	 * 批量刷新token
	 */
	@PostMapping("/refreshTokens")
	public AjaxResult refreshTokens(@RequestBody List<String> tokens) {
		log.info("收到刷新tokens请求，token数量为{}", tokens.size());
		tokens.stream().forEach(token -> {
			try {
				LoginUser loginUser = tokenService.getLoginUser(token);
				if (loginUser != null) {
					tokenService.refreshToken(loginUser);
				}
			} catch (Exception ex) {
				log.warn("刷新token失败，错误原因：" + ex.getMessage(), ex);
			}
		});

		AjaxResult result = AjaxResult.success();
		log.info("返回刷新tokens请求结果：{}", result);
		return result;
	}

}
